package com.ldcc.springcomponentdemo.spring_integration.basic;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;

import java.util.Scanner;

@SpringBootApplication
@EnableIntegration
public class SpringIntegrationBasicDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringIntegrationBasicDemoApplication.class, args);
    }

    // 定义一个点对点通道（DirectChannel）
    // 与NIO的Channel类似，只提供对消息本身的处理，不关注消息的生产与消费的实现
    @Bean
    public MessageChannel inputChannel() {
        return new DirectChannel();
    }

    // 应用启动后，通过命令行 Runner 向通道发送一条消息
    @Bean
    public CommandLineRunner sendRunner(MessageChannel inputChannel) {
        return args -> {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入消息（输入 exit 退出）：");

            while (true) {
                System.out.print("> ");
                String line = scanner.nextLine();
                if ("exit".equalsIgnoreCase(line)) {
                    System.out.println("程序结束");
                    System.exit(0);  // 也可以优雅退出
                }

                inputChannel.send(new GenericMessage<>(line));
            }
        };
    }

    // 定义一个消息处理器，当有消息发送到 inputChannel 时，方法被调用 即 消费者
    @ServiceActivator(inputChannel = "inputChannel")
    public void handleMessage(String payload) {
        System.out.println("Received: " + payload);
    }

}
